package net.fdukedom.epicurus.presentation.filters;

import net.fdukedom.epicurus.core.extensions.menu.MenuExtensionHandler;
import net.fdukedom.epicurus.presentation.SessionData;
import net.fdukedom.epicurus.presentation.wrappers.MenuItemWrapper;
import net.fdukedom.epicurus.resource.ExtensionHandler;
import net.fdukedom.epicurus.resource.ResourceDispatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Creates main menu.
 *
 * @author Dmitry Y. Kochelaev
 */
public class MainMenuFilter extends AbstractHttpFilter {

    private ResourceDispatcher resourceDispatcher = ResourceDispatcher.getInstance();

    protected void doFilter(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain
    ) throws IOException, ServletException {
        List<ExtensionHandler> handlers = resourceDispatcher.getExtensions("core.mainMenu");
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("isLoggedIn", request.getAttribute("isLoggedIn"));
        parameters.put("user", SessionData.getInstance(request).getUser());
        List<MenuItemWrapper> menuItems = new ArrayList<MenuItemWrapper>();
        for (ExtensionHandler handler : handlers) {
            Map<String, Object> result = handler.execute(parameters);
            if ((Boolean) result.get(ExtensionHandler.IS_EXTENSION_VISIBLE)) {
                menuItems.add(new MenuItemWrapper((String) result.get(MenuExtensionHandler.EXTENSION_TITLE),
                        (String) result.get(MenuExtensionHandler.EXTENSION_ACTION)));
            }
        }
        request.setAttribute("mainMenuItems", menuItems);
        filterChain.doFilter(request, response);
    }
}
